<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>

    <script src="./node_modules/react/umd/react.development.js"></script>
    <script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
    <script src="./node_modules/babel-standalone/babel.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <div id="root"></div>
    <script type="text/babel">
      ReactDOM.render(<h1>Hello, world!</h1>, document.getElementById('example'))
    </script>

    <script>
      // 虚拟dom
      function Element({ tagName, props, children }) {
        if (!(this instanceof Element)) {
          return new Element({ tagName, props, children })
        }
        this.tagName = tagName
        this.props = props || {}
        this.children = children || []
      }

      Element.prototype.render = function () {
        let el = document.createElement(this.tagName),
          props = this.props
        for (let propName in props) {
          let propValue = props[propName]
          if (Object.prototype.toString.call(propValue) === '[object Object]') {
            for (let name in propValue) {
              // console.log(Object.keys(propValue), Object.values(propValue), 'props')
              el.setAttribute(propName, ` ${name}: ${propValue[name]}`)
            }
          } else if (Array.isArray(propValue)) {
            el.setAttribute(propName, propValue.join(' '))
          } else if (Object.prototype.toString.call(propValue) === '[object Function]') {
            // el.setAttribute(propName, propValue)
            el.addEventListener('click', propValue)
          } else {
            el.setAttribute(propName, propValue)
          }
        }
        this.children.forEach(function (child) {
          var childEl = null
          if (child instanceof Element) {
            childEl = child.render()
          } else {
            childEl = document.createTextNode(child)
          }
          el.appendChild(childEl)
        })
        return el
      }

      let elem = Element({
        tagName: 'ul',
        props: { class: 'list' },
        children: [
          Element({
            tagName: 'li',
            props: {
              style: {
                width: '100px',
                border: '1px solid red',
              },
              class: ['box1', 'box2', 'box1'],
              onClick: () => {
                console.log(1)
              },
            },
            children: ['item1'],
          }),
          Element({
            tagName: 'li',
            props: {
              style: {
                color: 'red',
              },
            },
            children: ['item2'],
          }),
        ],
      })
      // console.log(elem.render(), 'elem.render()')
      document.querySelector('body').appendChild(elem.render())
    </script>
  </body>
</html>
